<template>
  <div class="app-container">
    <!-- :data 用于存放请求数据回来的数组 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-lodaing-text="数据加载中"
      fit
      border
      highlight-current-row
      stripe
      style="width:50%;"
    >
      <el-table-column
        prop="title"
        label="房源标题"
        min-width="60%"
        align="center"
      >
      </el-table-column>

      <el-table-column
        label="操作"
        min-width="40%"
        align="center"
      >
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="success"
              size="small"
              icon="el-icon-search"
              plain
              @click="toEdit(scope.row.houseId)"
            >查看</el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              plain
              @click="removeDataById(scope.row.houseId)"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import star from '@/api/star';
export default {
  // 定义数据
  data() {
    return {
      listLoading: true, // 是否显示loading信息
      list: null, // 数据列表
      userId: this.$store.state.user.userId
    };
  },
  computed: {
    ...mapGetters(['name', 'userId'])
  },
  // 当前页面加载时获取数据
  created() {
    this.fetchData();
  },
  // 调用api层获取数据库中的数据
  methods: {
    // 页面跳转
    toEdit(id) {
      this.$router.push('/comment/edit/' + id);
    },
    // 获取数据
    fetchData() {
      this.listLoading = true;
      star
        .getStar(this.userId)
        // 请求成功
        .then(response => {
          if (response.success === true) {
            this.list = response.data.items;
          }
          this.listLoading = false;
        })
        // 请求失败
        .catch(() => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          });
        });
    },
    // 删除数据
    removeDataById(id) {
      this.$confirm('此操作将永久删除该记录，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 点击确定执行then()
        .then(() => {
          return star.removeStarById(id, this.userId);
        })
        .then(() => {
          this.fetchData();
          this.$message({
            type: 'success',
            message: '删除成功'
          });
        })
        // 点击取消执行catch()
        .catch(response => {
          if (response === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            });
          }
        });
    }
  }
};
</script>

<style>
.el-table th.gutter {
  display: table-cell !important;
}
.el-table .cell {
  white-space: pre-line;
}
</style>